package com.jiang.jixiang.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.jiang.jixiang.R;
import com.jiang.jixiang.bean.SellerInfoBean;
import com.jiang.jixiang.databinding.ActivityMainBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.ui.fragment.IndexFragment;
import com.jiang.jixiang.ui.fragment.InviteFragment;
import com.jiang.jixiang.ui.fragment.MyWalletFragment;
import com.jiang.jixiang.ui.fragment.OrderFragment;
import com.jiang.jixiang.ui.fragment.UserCenterFragment;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.permission.AppActivityTarget;
import com.ws.universal.tools.permission.PermissionListener;
import com.ws.universal.tools.permission.SettingExecutor;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.PermissionUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;
import com.ws.universal.tools.utils.glide.GlideUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements NetWorkListener, PermissionListener, BottomNavigationView.OnNavigationItemSelectedListener /*CameraListener*/ {

    private ActivityMainBinding binding;

    private int requestCodeScan = 1000;

    private List<Fragment> mFragmentList;

    @Override
    protected void initCreate(Bundle savedInstanceState) {

        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBusUtil.resgisterEventBus(this);


    }

    @Override
    protected void initView() {

        //uploadApp();

        binding.inclideMain.navigationView.setItemIconTintList(null);
        binding.inclideMain.navigationView.setItemBackground(null);
        binding.inclideMain.navigationView.setOnNavigationItemSelectedListener(this);

        mFragmentList = new ArrayList<>();
        mFragmentList.add(new IndexFragment());
        mFragmentList.add(new OrderFragment());
        mFragmentList.add(new MyWalletFragment());
        mFragmentList.add(new UserCenterFragment());
        initGetmFragmentListChild();

        binding.inclideMain.navigationView.setSelectedItemId(R.id.navigation_index);



        /*扫码界面*/
        binding.btnScan.setOnClickListener(view -> {
            if (CacheUtils.getBoolean(Constants.isLogin)) {
                PermissionUtils.getInstance().CheckPermissions(this, requestCodeScan, PermissionUtils.Permission_Camera);
            } else {
                pageJump(LoginActivity.class);
            }


        });


        binding.rlShowMerchant.setOnClickListener(v -> {
            getSellerInfoBean();
        });
        binding.llShowMerchant.setOnClickListener(v -> {
            getSellerInfoBean();
        });

    }

    private void getSellerInfoBean() {
        if (sellerInfoBean != null) {
            Bundle bundle = new Bundle();
            bundle.putString("id", sellerInfoBean.getId());
            pageJump(NearbySellerInfoActivity.class, bundle);
        } else {
            ToastUtils.showShort(" sellerInfoBean null");
        }

    }

    private IndexFragment indexFragment;
    private OrderFragment orderFragment;
    private MyWalletFragment myWalletFragment;
    private UserCenterFragment userCenterFragment;

    private void initGetmFragmentListChild() {
        indexFragment = (IndexFragment) mFragmentList.get(0);
        orderFragment = (OrderFragment) mFragmentList.get(1);
        myWalletFragment = (MyWalletFragment) mFragmentList.get(2);
        userCenterFragment = (UserCenterFragment) mFragmentList.get(3);
    }


    public class onPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
        @Override
        public void onPageSelected(int position) {
            binding.inclideMain.navigationView.setSelectedItemId(binding.inclideMain.navigationView.getMenu().getItem(position).getItemId());


        }
    }


    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {


           /* case ApiUrl.version_Api_ID:
                JSONObject android_version = data.optJSONObject("android_version");
                if (AppUtils.getAppVersionCode() < android_version.optInt("version")) {
                    if (data.optInt("update") == 1) {
                        upDateApp(data.optString("url"), "", true);
                    } else {
                        upDateApp(data.optString("url"), "", false);
                    }
                }

                break;*/
        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }


    /*** App更新 */
    private void upDateApp(String apkUrl, String content, boolean isCompulsory) {
        PubDiaUtils.getInstance().showOneBtnDialog(getActivity(), getString(R.string.new_version_discovered), content, getString(R.string.update_now), isCompulsory, new PubDiaUtils.PublicDiaologCallback() {
            @Override
            public void onConfirm() {
                Uri uri = Uri.parse(apkUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);

            }

            @Override
            public void onCancel() {

            }
        });
    }

    private SellerInfoBean sellerInfoBean;

    @Subscribe(threadMode = ThreadMode.MAIN)  //3.0之后，需要加注解
    public void onEventMainThread(BaseBusData data) {
        switch (data.action) {
            case BusCode.showMainSellerInfo:
                sellerInfoBean = (SellerInfoBean) data.object;
                if (sellerInfoBean != null) {
                    binding.tvSellerName.setText(sellerInfoBean.getName());
                    binding.tvSellerAddress.setText(sellerInfoBean.getAddress());
                    binding.tvItemDistance.setText(sellerInfoBean.getDistance());
                    //binding.tvSellerTime.setText(StringUtils.getString(sellerInfoBean.getShop_start(), "-", sellerInfoBean.getShop_end()));
                    binding.tvItemHire.setText(StringUtils.getString(sellerInfoBean.getBorrow_num()));
                    binding.tvItemReturn.setText(StringUtils.getString(sellerInfoBean.getReturn_num()));
                    //binding.tvSellerTel.setText(StringUtils.getString(sellerInfoBean.getTel()));

                    GlideUtils.CreateImageRound(sellerInfoBean.getLogo(), binding.imgSeller, R.mipmap.icon_defult_nearbylist, R.mipmap.icon_defult_nearbylist);

                }
                if (binding.llShowMerchant.getVisibility() == View.GONE) {
                    binding.llShowMerchant.setVisibility(View.VISIBLE);
                    binding.rlShowMerchant.setVisibility(View.VISIBLE);
                }

                break;
            case BusCode.hindMainView:
                if (binding.llShowMerchant.getVisibility() == View.VISIBLE) {
                    binding.llShowMerchant.setVisibility(View.GONE);
                    binding.rlShowMerchant.setVisibility(View.GONE);
                }

                break;


            case BusCode.showMainTip:
                indexFragment.startPolling(CacheUtils.getString(Constants.order_no));
                break;
            case BusCode.LogOut:
                //stopPolling();
                //binding.llLeaseing.setVisibility(View.GONE);
                break;
            case BusCode.LogIn:
                switch (currentPosition) {
                    case 0:
                        binding.inclideMain.navigationView.setSelectedItemId(R.id.navigation_index);
                        break;
                    case 1:
                        binding.inclideMain.navigationView.setSelectedItemId(R.id.navigation_invite);
                        break;
                    case 2:
                        binding.inclideMain.navigationView.setSelectedItemId(R.id.navigation_wallet);
                        break;
                    case 3:
                        binding.inclideMain.navigationView.setSelectedItemId(R.id.navigation_me);
                        break;
                }
                break;

            case BusCode.updateUserInfo:
                if (userCenterFragment != null) {
                    userCenterFragment.loadData();
                }
                break;
        }

    }


    @Override
    public void onPermissionSucceed(int requestCode, @NonNull List<String> grantPermissions) {

        if (requestCode == requestCodeScan) {
            pageJump(ScanActivity.class);
        }

    }

    @Override
    public void onPermissionFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        PubDiaUtils.getInstance().showTwoBtnDialog(getContext(), getString(R.string.permission_hit), getString(R.string.permission_content), getString(R.string.cancel), getString(R.string.sure), new PubDiaUtils.PublicDiaologCallback() {
            @Override
            public void onConfirm() {
                if (mSettingService == null) {
                    mSettingService = new SettingExecutor(new AppActivityTarget(getActivity()), 300);
                }
                mSettingService.execute();
            }

            @Override
            public void onCancel() {

            }
        });
    }


    @Override
    public void onBackPressed() {
        if (binding.llShowMerchant.getVisibility() == View.VISIBLE) {
            binding.llShowMerchant.setVisibility(View.GONE);
            binding.rlShowMerchant.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }

    }

    @Override
    protected void FinishDesTroy() {
        EventBusUtil.unResgisterEventBus(this);
        ManageActivity.removeActivity(this.getClass().getSimpleName());
        //stopPolling();
    }

    private int currentPosition = 0;

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragment(transaction);
        switch (menuItem.getItemId()) {
            case R.id.navigation_index:
                currentPosition = 0;
                if (indexFragment.isAdded()) {
                    transaction.show(indexFragment);
                } else {
                    transaction.add(R.id.viewHostFragment, indexFragment);
                }
                break;
            case R.id.navigation_invite:
                currentPosition = 1;
                if (CacheUtils.getBoolean(Constants.isLogin)) {
                    if (orderFragment.isAdded()) {
                        transaction.show(orderFragment);
                    } else {
                        transaction.add(R.id.viewHostFragment, orderFragment);
                    }
                } else {
                    pageJump(LoginActivity.class);
                }
                break;

            case R.id.navigation_wallet:
                currentPosition = 2;
                if (CacheUtils.getBoolean(Constants.isLogin)) {
                    if (myWalletFragment.isAdded()) {
                        transaction.show(myWalletFragment);
                    } else {
                        transaction.add(R.id.viewHostFragment, myWalletFragment);
                    }
                    if (myWalletFragment != null) {
                        myWalletFragment.loadData();
                    }
                } else {
                    pageJump(LoginActivity.class);
                }
                break;
            case R.id.navigation_me:
                currentPosition = 3;
                LogcatUtils.e(" isLogin " + CacheUtils.getBoolean(Constants.isLogin));
                if (CacheUtils.getBoolean(Constants.isLogin)) {
                    if (userCenterFragment.isAdded()) {
                        transaction.show(userCenterFragment);
                    } else {
                        transaction.add(R.id.viewHostFragment, userCenterFragment);
                    }
                    if (userCenterFragment != null) {
                        userCenterFragment.loadData();
                    }
                } else {
                    pageJump(LoginActivity.class);
                }


                break;
        }
        transaction.commitAllowingStateLoss();
        return true;
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (indexFragment.isAdded()) {
            transaction.hide(indexFragment);
        }
        if (orderFragment.isAdded()) {
            transaction.hide(orderFragment);
        }

        if (myWalletFragment.isAdded()) {
            transaction.hide(myWalletFragment);
        }
        if (userCenterFragment.isAdded()) {
            transaction.hide(userCenterFragment);
        }


    }
}